<template>
  <div class="app-container">
    <!-- 查询的表单-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="书本编号" prop="bookId">
        <el-input
          v-model="queryParams.bookId"
          placeholder="请输入书本编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书本名称" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入书本名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="书本价格区间">
        <el-col :span="11">
          <el-input
            v-model="queryParams.bookPriceStart"
            placeholder="请输入起始价格"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-input
            v-model="queryParams.bookPriceEnd"
            placeholder="请输入最大价格"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="录入人" prop="belongTo">
        <el-select
          v-model="queryParams.belongTo"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="belongToloading">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="书本评价" prop="evaluateType">
        <el-select v-model="queryParams.evaluateType" placeholder="请选择">
          <el-option
            v-for="dict in dict.type.evaluate_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--按钮组-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['library:book:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"

        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!--数据正文-->
    <el-table
      @selection-change="handleSelectionChange"
      v-loading="loading"
      :data="tableData"
      style="width: 100%">

      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="bookId"
        label="书本编号"
        v-if="columns[0].visible"
        width="180">
      </el-table-column>
      <el-table-column
        prop="bookName"
        label="书名"
        v-if="columns[1].visible"
        width="180">
      </el-table-column>
      <el-table-column
        prop="bookPrice"
        label="书本价格"
        v-if="columns[2].visible"
        width="180">
      </el-table-column>
      <el-table-column
        prop="bookDesc"
        show-overflow-tooltip
        v-if="columns[3].visible"
        label="书本描述">
      </el-table-column>

      <el-table-column
        prop="bookUrl"
        v-if="columns[4].visible"
        label="书本封面">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.bookUrl" :src="scope.row.bookUrl" height="60px" width="40px"/>
        </template>
      </el-table-column>

      <el-table-column
        prop="user.nickName"
        v-if="columns[5].visible"
        label="录入人">

        <template slot-scope="scope">
          <el-tag v-if="scope.row.user" effect="dark" type="success">{{scope.row.user.nickName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="书本评价" align="center" prop="name" v-if="columns[6].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.evaluate_type" :value="scope.row.evaluateType"/>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <!--分页插件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--书本管理新增、修改-->
    <el-dialog title="书本管理" :visible.sync="dialogFormVisible">
      <el-form ref="form" status-icon :rules="rules" :model="form" label-width="80px">

        <el-form-item label="书本编号">
          <el-input v-model="form.bookId" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书本名称" prop="bookName">
          <el-input v-model="form.bookName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="书本价格" prop="bookPrice">
          <el-input v-model="form.bookPrice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书本类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择">
            <el-option
              v-for="item in bookTypeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="书本评价" prop="evaluateType">
          <el-select v-model="form.evaluateType" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.evaluate_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="书本描述">
         <!-- <el-input v-model="form.bookDesc" autocomplete="off"></el-input>-->
          <editor :value="form.bookDesc" v-model="form.bookDesc" height="100"/>
        </el-form-item>

        <el-form-item label="书本封面">
          <image-upload :value="form.bookUrl" v-model="form.bookUrl"/>
        </el-form-item>

      </el-form>

      <el-table
        :data="form.subScribeList"
        border
        style="width: 100%">
        <el-table-column
          prop="subscriber"
          label="订阅人"
          width="180">
        </el-table-column>
        <el-table-column
          prop="subscribeTime"
          label="订阅时间"
          width="180">
        </el-table-column>
        <el-table-column
          prop="subscribeStar"
          label="期待值">
          <template slot-scope="scope">
            <el-rate
              v-model="scope.row.subscribeStar"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}">
            </el-rate>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 书本导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <div id="main" style="width: 1024px;height: 800px"></div>
  </div>

</template>

<script>
  import {getToken} from "@/utils/auth";
  import { getBookTypes,getBookList,addBook ,getBookById,editBook,deleteMyBooks,getSubScribeCount} from "@/api/book/index";
  import { listUserLikeNickName } from "@/api/system/user";

  export default {
    name: "index",
    dicts: ['evaluate_type'],
    created() {
      this.getList()
      //调用api方法发送后端请求
      /*getBookList.then(res=>{
        this.tableData=res.data()
      })*/
      this.loadAllBookType()
    },

    mounted() {
      getSubScribeCount().then(res=>{
        this.drawEcharts(res.data)
      })
      /*this.drawEcharts([
        { value: 40, name: 'rose 1' },
        { value: 38, name: 'rose 2' },
        { value: 32, name: 'rose 3' },
        { value: 30, name: 'rose 4' },
        { value: 28, name: 'rose 5' }
      ]);*/
    },
    data() {
      var checkPrice = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('价格不能为空'));
        }
        setTimeout(() => {
          var reg1 = /^[0-9]*$/;
          var reg2 = /^(-?\d+)(\.\d+)?$/;

          if (!reg1.test(value) && !reg2.test(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value <0) {
              callback(new Error('必须大于0'));
            } else {
              callback();
            }
          }
        }, 1000);
      };


      return {
        userList:[],

        //远程加载下拉用户
        belongToloading:false,
        showSearch:true,
        // 列信息
        columns: [
          { key: 0, label: `书本编号`, visible: true },
          { key: 1, label: `书名`, visible: true },
          { key: 2, label: `书本价格`, visible: true },
          { key: 3, label: `书本描述`, visible: true },
          { key: 4, label: `书本封面`, visible: true },
          { key: 5, label: `录入人`, visible: true },
          { key: 6, label: `书本评价`, visible: true }
        ],
        rules:{
          bookName:[
            {required:true,message:'图书名不能为空',trigger:'blur'},
            /*{type:'enum',message: '测试规则，图书只能在一下范围内：',
              enum:['《三国》','《红楼梦》','《哈姆雷特》'],trigger:'blur'}*/
          ],
          bookPrice:[
            {required:true,validator: checkPrice,trigger:'blur'}
          ]
        },
        bookTypeList:[
        ],
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/book/importBook"
        },
        form:{},
        dialogFormVisible:false,
        loading: true,
        name: 'Virgil',
        tableData: [],
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bookId: undefined,
          bookName: undefined,
          bookPriceStart: undefined,
          bookPriceEnd:undefined,
          bookDesc: undefined,
          belongTo:undefined,
          evaluateType: undefined
        },

      }
    },
    methods: {
      /** 重置按钮操作 */
      resetQuery() {

        this.resetForm("queryForm");
        this.handleQuery();
      },
      remoteMethod(query){
        this.belongToloading=true;
        //发送一个请求，携带query,模糊查询所有的用户列表

        listUserLikeNickName({nickName:query}).then(res=>{
          this.userList=res.data;
          this.belongToloading=false;
        })
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      loadAllBookType(){
        getBookTypes().then(res=>{
          this.bookTypeList=res.data
        })
      },
      drawEcharts(data){
        var chartDom = document.getElementById('main');
        var myChart = this.$echarts.init(chartDom);
        var option;

        option = {
          legend: {
            top: 'bottom'
          },
          toolbox: {
            show: true,
            feature: {
              mark: { show: true },
              dataView: { show: true, readOnly: false },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          series: [
            {
              name: 'Nightingale Chart',
              type: 'pie',
              radius: [50, 250],
              center: ['50%', '50%'],
              roseType: 'area',
              itemStyle: {
                borderRadius: 8
              },
              data: data
            }
          ]
        };

        option && myChart.setOption(option);

      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('book/export', {
          ...this.queryParams
        }, `图书导出_${new Date().getTime()}.xlsx`)
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('book/importTemplate', {
        }, `user_template_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$modal.msgSuccess("文件导入成功！");
        //this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      handleSelectionChange(rows){
        this.ids=rows.map(item =>item.bookId);
      },
      handleDelete(row){

        const bookIds = row.bookId || this.ids;
        this.$modal.confirm('是否确认删除用户编号为"' + bookIds + '"的数据项？').then(function() {
          return deleteMyBooks(bookIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleUpdate(row){
        this.dialogFormVisible=true;

        getBookById(row.bookId).then(res=>{
          this.form=res.data
        })
      },
      submitForm(){

        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.bookId!==undefined){

              editBook(this.form).then(res=>{
                this.$modal.msgSuccess(res.msg);
                this.dialogFormVisible=false;
                this.getList();
              })
            }else {
              addBook(this.form).then(res=>{
                this.$modal.msgSuccess(res.msg);
                this.dialogFormVisible=false;
                this.getList();
              })
            }
          } else {
            this.$modal.msgWarning('请按照规则填写相应的字段')
            return false;
          }
        });
      },
      // 表单重置
      reset() {
        this.form = {
          bookId: undefined,
          bookName: undefined,
          bookPrice: undefined,
          bookDesc: undefined,
          bookUrl:undefined,
          subScribeList:[],
          typeId:undefined,
          evaluateType:undefined
        };
        this.resetForm("form");
        this.$refs['form'].resetFields();
      },
      handleCancel(){
        this.reset();
        this.dialogFormVisible=false;
      },
      handleAdd(){
        this.dialogFormVisible=true;
        this.reset();
      },
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        getBookList(this.queryParams).then(response => {
          this.tableData=response.rows;
          this.total = response.total;
          this.loading=false;
        })
        /*listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );*/
      },
    }
  }
</script>

<style scoped>

</style>
